import 'package:bitcoin_mine/common/global.dart';
import 'package:bitcoin_mine/model/mine_info.dart';
import 'package:bitcoin_mine/controllers/contract_service_controller.dart';
import 'package:bitcoin_mine/services/in_app_purchase_service.dart';
import 'package:bitcoin_mine/widgets/restore_purchases_section.dart';
import 'package:bitcoin_mine/widgets/rolling_number_units.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../controllers/contract_controller.dart';
import '../l10n/app_localizations.dart';

class ContractsListWidget extends StatelessWidget {
  const ContractsListWidget({super.key});

  // 排序按钮的GlobalKey
  static final GlobalKey sortingButtonKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    final ContractController controller = Get.find();
    final contractServiceController = Get.put(ContractServiceController());
    final InAppPurchaseService inAppPurchaseService =
        Get.find<InAppPurchaseService>();
    final l10n = AppLocalizations.of(context);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 合约列表
          Obx(() {
            // final contracts = controller.allContracts;
            if (Global.contracts.isEmpty) {
              return Column(
                children: [
                  SizedBox(height: 10.h),
                  GestureDetector(
                    onTap: () {
                      contractServiceController.watchAds().then((value) {
                        controller.updateContractAmounts();
                      });
                    },
                    child: Image.asset(
                      'assets/images/pic_watch_ads.png',
                      width: 374.w,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Obx(() {
                    if (Global.mineInfo.value?.free_contract == null) {
                      return Column(
                        children: [
                          SizedBox(height: 15.h),
                          GestureDetector(
                            onTap: () {
                              contractServiceController
                                  .receiveFreeContract()
                                  .then((value) {
                                    controller.updateContractAmounts();
                                  });
                            },
                            child: Image.asset(
                              'assets/images/pic_free_contract_inactive.png',
                              width: 374.w,
                              fit: BoxFit.cover,
                            ),
                          ),
                        ],
                      );
                    } else {
                      if (Global.mineInfo.value?.free_contract?.status == 1) {
                        return Column(
                          children: [
                            SizedBox(height: 15.h),
                            Image.asset(
                              'assets/images/pic_free_contract_active.png',
                              width: 374.w,
                              fit: BoxFit.cover,
                            ),
                          ],
                        );
                      } else {
                        return Container();
                      }
                    }
                  }),

                  SizedBox(height: 10.h),
                  // 热门订阅项目
                  Obx(() {
                    final info = Global.mineInfo.value;
                    if (info == null) {
                      return const SizedBox.shrink();
                    }

                    // 收集前两个商品（按组顺序）
                    final List<Good> allGoods = [
                      ...info.goods_map.group1,
                      ...info.goods_map.group2,
                      ...info.goods_map.group3,
                      ...info.goods_map.group4,
                    ];
                    if (allGoods.isEmpty) return const SizedBox.shrink();
                    final List<Good> popular =
                        allGoods.length >= 2
                            ? allGoods.sublist(0, 2)
                            : allGoods;

                    String periodText(int circle) {
                      if (circle == 1) return 'month';
                      if (circle == 12) return 'year';
                      return '$circle months';
                    }

                    Widget card(Good g) {
                      final good = Global.goods.firstWhere(
                        (element) => element.product_id == g.product_id,
                      );
                      final ProductDetails? productInfo = inAppPurchaseService
                          .getProductInfo(good.product_id);
                      final String periodText = inAppPurchaseService.periodText(
                        good.circle,
                      );
                      final String priceText =
                          '${good.discount_price != null ? '${productInfo?.currencySymbol}${good.discount_price}' : '${productInfo?.price}'}/';

                      final String nextText =
                          'The next: ${productInfo?.price}/$periodText';
                      return Expanded(
                        child: Container(
                          margin: EdgeInsets.only(right: 12.w),
                          padding: EdgeInsets.symmetric(
                            horizontal: 14.w,
                            vertical: 12.h,
                          ),
                          decoration: BoxDecoration(
                            image: const DecorationImage(
                              image: AssetImage(
                                'assets/images/bg_selection.png',
                              ),
                              fit: BoxFit.fill,
                            ),
                          ),
                          child: Row(
                            children: [
                              Image.asset(
                                'assets/images/icon_contract.png',
                                width: 26.r,
                                height: 26.r,
                              ),
                              SizedBox(width: 8.w),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  RichText(
                                    text: TextSpan(
                                      children: [
                                        TextSpan(
                                          text: priceText,
                                          style: TextStyle(
                                            color: const Color(0xFF05FFFD),
                                            fontSize: 18.sp,
                                            fontWeight: FontWeight.w700,
                                          ),
                                        ),
                                        TextSpan(
                                          text: '/$periodText',
                                          style: TextStyle(
                                            color: const Color(0xFF05FFFD),
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Text(
                                    nextText,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 12.sp,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                  Text(
                                    '${g.hashrate.toStringAsFixed(2)} Gh/s',
                                    style: TextStyle(
                                      color: const Color(0xFF05FFFD),
                                      fontSize: 12.sp,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    }

                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 4.w),
                          child: Text(
                            'Popular Subscriptions',
                            style: TextStyle(
                              color: const Color(0xFF05FFFD),
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Row(
                          children: [
                            ...popular.map((g) => card(g)),
                            // card(popular[0]),
                            // if (popular.length > 1) card(popular[1]),
                          ],
                        ),
                      ],
                    );
                  }),
                  SizedBox(height: 10.h),
                  RestorePurchasesSection(),
                ],
              );
            }

            return Column(
              children: [
                // 总加速值和排序按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 总加速值
                    Obx(
                      () => Row(
                        children: [
                          Image(
                            image: AssetImage("assets/images/icon_speed.png"),
                            width: 32.r,
                            height: 32.r,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '${l10n.total}: ${Global.totalHashrate.value.toString()} Gh/s',
                            style: TextStyle(
                              color: const Color(0xFF05FFFD),
                              fontSize: 14.sp,
                            ),
                          ),
                        ],
                      ),
                    ),

                    // 排序按钮
                    GestureDetector(
                      key: sortingButtonKey,
                      onTap: () => controller.toggleSortingMenu(),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 6.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFF05FFFD),
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(
                            color: const Color(0xFF000000),
                            width: 1,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.menu_outlined,
                              color: const Color(0xFF061125),
                              size: 16.sp,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              l10n.sorting,
                              style: TextStyle(
                                color: const Color(0xFF061125),
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15.h),
                Column(
                  children:
                      Global.contracts.map((contract) {
                        final statusText =
                            controller.isContractExpired(contract)
                                ? 'EXPIRED'
                                : 'ACTIVE';

                        // amount is computed inside Obx below

                        return Container(
                          height: 151.h,
                          margin: EdgeInsets.only(bottom: 12.h),
                          padding: EdgeInsets.only(
                            left: 15.w,
                            right: 10.w,
                            top: 6.h,
                            bottom: 0.h,
                          ),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                "assets/images/bg_contract_card.png",
                              ),
                              fit: BoxFit.fill,
                            ),
                          ),
                          child: Stack(
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  // 标题和状态
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Row(
                                        children: [
                                          SizedBox(width: 20.w),
                                          Text(
                                            controller.getContractTypeText(
                                              contract,
                                            ),
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16.sp,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),

                                  SizedBox(height: 12.h),

                                  // 比特币数量
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Image(
                                        image: AssetImage(
                                          "assets/images/icon_bit_coin.png",
                                        ),
                                        width: 36.r,
                                        height: 36.r,
                                      ),
                                      SizedBox(width: 8.w),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          SizedBox(height: 3.h),
                                          Obx(() {
                                            final amount =
                                                controller
                                                    .contractAmountUnits[contract
                                                    .id] ??
                                                BigInt.zero;
                                            return RollingNumberUnits(
                                              units: amount,
                                              scale: 15,
                                              prefix: '+ ',
                                              suffix: ' btc',
                                              style: TextStyle(
                                                color: const Color(0xFF05FFFD),
                                                fontSize: 20.sp,
                                              ),
                                            );
                                          }),

                                          SizedBox(height: 5.h),
                                          Obx(() {
                                            final remainingHours =
                                                controller
                                                    .contractRemainingHours[contract
                                                    .id] ??
                                                0;

                                            final remainingMinutes =
                                                controller
                                                    .contractRemainingMinutes[contract
                                                    .id] ??
                                                0;

                                            final isExpired = controller
                                                .isContractExpired(contract);
                                            // 过期时间
                                            return Text(
                                              isExpired
                                                  ? l10n.expired
                                                  : remainingMinutes > 0
                                                  ? '${l10n.itWillExpireIn} $remainingHours ${l10n.hours} and $remainingMinutes minutes'
                                                  : '${l10n.itWillExpireIn} $remainingHours ${l10n.hours}',
                                              style: TextStyle(
                                                color: const Color(0xFF05FFFD),
                                                fontSize: 14.sp,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            );
                                          }),
                                        ],
                                      ),
                                    ],
                                  ),

                                  SizedBox(height: 20.h),

                                  // 加速值
                                  Row(
                                    children: [
                                      Expanded(
                                        child: Row(
                                          children: [
                                            Text(
                                              statusText == 'ACTIVE'
                                                  ? l10n.active
                                                  : l10n.expired,
                                              style: TextStyle(
                                                color: const Color(0xFF05FFFD),
                                                fontSize: 16.sp,
                                                fontWeight: FontWeight.w600,
                                              ),
                                            ),
                                            SizedBox(width: 4.w),
                                            ClipOval(
                                              child: Container(
                                                width: 12.w,
                                                height: 12.w,
                                                color:
                                                    statusText == 'ACTIVE'
                                                        ? const Color(
                                                          0xFF05FFFD,
                                                        )
                                                        : const Color(
                                                          0xFFFF3C22,
                                                        ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),

                                      Image(
                                        image: AssetImage(
                                          "assets/images/icon_speed.png",
                                        ),
                                        width: 26.r,
                                        height: 26.r,
                                      ),
                                      SizedBox(width: 4.w),
                                      Text(
                                        '${contract.hashrate.toStringAsFixed(2)} Gh/s',
                                        style: TextStyle(
                                          color: const Color(0xFF05FFFD),
                                          fontSize: 14.sp,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),

                                      SizedBox(width: 4.w),
                                    ],
                                  ),
                                ],
                              ),
                              // 可以根据需要添加问号图标
                              Positioned(
                                top: 10.h,
                                right: 0.w,
                                child: GestureDetector(
                                  onTap:
                                      () => _showContractGuide(context, l10n),
                                  child: Icon(
                                    Icons.help,
                                    color: const Color(0xFF05FFFD),
                                    size: 20.sp,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        );
                      }).toList(),
                ),
              ],
            );
          }),
        ],
      ),
    );
  }

  void _showContractGuide(BuildContext context, AppLocalizations l10n) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      builder: (ctx) {
        return SafeArea(
          child: Padding(
            padding: EdgeInsets.only(
              left: 16.w,
              right: 16.w,
              top: 16.h,
              bottom: 16.h + MediaQuery.of(ctx).viewInsets.bottom,
            ),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Container(
                      width: 44.w,
                      height: 4.h,
                      decoration: BoxDecoration(
                        color: Colors.black12,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),
                  SizedBox(height: 12.h),
                  Center(
                    child: Text(
                      l10n.contractGuideTitle,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: const Color(0xFF061125),
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  SizedBox(height: 12.h),
                  Text(
                    l10n.contractGuideP1,
                    style: TextStyle(
                      color: const Color(0xFF061125).withOpacity(0.8),
                      fontSize: 14.sp,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 10.h),
                  Text(
                    l10n.contractGuideP2,
                    style: TextStyle(
                      color: const Color(0xFF061125).withOpacity(0.8),
                      fontSize: 14.sp,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 10.h),
                  Text(
                    l10n.contractGuideP3,
                    style: TextStyle(
                      color: const Color(0xFF061125).withOpacity(0.8),
                      fontSize: 14.sp,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 10.h),
                  Text(
                    l10n.contractGuideP4,
                    style: TextStyle(
                      color: const Color(0xFF061125).withOpacity(0.8),
                      fontSize: 14.sp,
                      height: 1.5,
                    ),
                  ),
                  SizedBox(height: 16.h),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
